package com.cmwa.scbp.sys.msg.util;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;

import com.cmwa.scbp.sys.dictionary.entity.DictionaryVo;
import com.cmwa.scbp.utils.cached.DictionaryCached;

public class StringUtil {
	
	/** 特殊字符UnicodeBlock */
	public static final Set<Character.UnicodeBlock> SPCIAL_SYMBOL_BLOCK = new HashSet<Character.UnicodeBlock>(){

		/**  */
		private static final long serialVersionUID = 1L;
		{
			add(Character.UnicodeBlock.GEOMETRIC_SHAPES);
			add(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS);
			add(Character.UnicodeBlock.DINGBATS);
			add(Character.UnicodeBlock.CJK_COMPATIBILITY);
			add(Character.UnicodeBlock.GENERAL_PUNCTUATION);
			add(Character.UnicodeBlock.BLOCK_ELEMENTS);
			add(Character.UnicodeBlock.LATIN_1_SUPPLEMENT);
			add(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION);
			add(Character.UnicodeBlock.ARABIC);
			add(Character.UnicodeBlock.LETTERLIKE_SYMBOLS);
			add(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS);
			add(Character.UnicodeBlock.MATHEMATICAL_OPERATORS);
			add(Character.UnicodeBlock.ARROWS);
			add(Character.UnicodeBlock.GEORGIAN);
			add(Character.UnicodeBlock.TAMIL);
			add(Character.UnicodeBlock.CURRENCY_SYMBOLS);
			add(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS);
			add(Character.UnicodeBlock.GREEK);
			add(Character.UnicodeBlock.THAI);
			add(Character.UnicodeBlock.HIGH_SURROGATES);
			add(Character.UnicodeBlock.LOW_SURROGATES);
			add(Character.UnicodeBlock.IPA_EXTENSIONS);
			add(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO);
		}
	};
	
	public static String toString (Object obj){
	    if (null == obj)
	    {
	    	return "";
	    }
	    return obj.toString();
	}
	
	/**
	 * 根据传入字符，判断是否删除最后一个字符
	 * @param charAt
	 * @param param		
	 * @return
	 */
	public static String deleteLastChar(char charAt, String param) {
		StringBuffer buffer = new StringBuffer(param);
		if (StringUtils.isNotBlank(param)) {
			if (charAt == (param.charAt(param.length() - 1))) {
				buffer.deleteCharAt(param.length() - 1);
			}
		}
		return buffer.toString();
	}
	
	/**
	 * 根据传入字符，判断是否删除最后几个字符
	 * @param charAt
	 * @param param		
	 * @return
	 */
	public static String deleteLastChar(char charAt, String param,int length) {
		if (param == null || param == "") {
			return "";
		}
		StringBuffer buffer = new StringBuffer(param);
		if (StringUtils.isNotBlank(param)) {
			if(param.length()>1){
				char str=param.charAt(param.length() - 2);
				char str1=param.charAt(param.length() - 1);
				if (charAt == str) {
					buffer.deleteCharAt(param.length() - 2);
				}else if(charAt == str1){
					buffer.deleteCharAt(param.length() - 1);
				}
			}
		}
		return buffer.toString();
	}
	
	
	
	public static String replaceNullOrEmpty(Object obj){
		if(obj==null){
			return "";
		}
		if(!(obj instanceof String)){
			return (obj+"").trim();
		}
		return obj.toString().trim();
	}
	
	public static String replaceNullOrEmpty(String obj){
		if(obj==null){
			return "";
		}
		return obj.trim();
	}
	
	public static String replaceNullOrEmptyNVL(Object obj,Object obj2){
		if(obj==null){
			obj="";
		}
		if(obj2==null){
			obj2="";
		}
		return replaceNullOrEmptyNVL(obj+"",obj2+"");
	}
	
	public static String replaceNullOrEmptyNVL(String obj,String obj2){
		
		if(StringUtils.isNotBlank(obj)){
			return obj.trim();
		}else{
			if(StringUtils.isNotBlank(obj2)){
				return obj2.trim();
			}
		}
		
		return "";
	}	/**
	 * SEPARATOR_01[ , ]
	 */
	public static final String SEPARATOR_01=",";

	public static String[] split(String res,String separator){
		if(res==null){
			res="";
		}else{
			res=res.trim();
		}
		if(separator==null){
			separator="";
		}else{
			separator=separator.trim();
		}
		return res.split(separator);
	}
	
	/**
	 * SURROUND_01[ ' ]
	 */
	public static final String SURROUND_01="'";
	
	public static String merge(String[] res,String surround,String separator){
		if(res==null || res.length==0){
			return "";
		}
		if(surround==null){
			surround="";
		}else{
			surround=surround.trim();
		}
		if(separator==null){
			separator="";
		}else{
			separator=separator.trim();
		}
		
		StringBuffer sb=new StringBuffer("");
		
		int size=res.length;
		for(int i=0;i<size;i++){
			sb.append(surround);
			sb.append(res[i]);
			sb.append(surround);
			if(i!=(size-1)){
				sb.append(separator);
			}
		}
		
		return sb.toString();
	}
	
	public static String merge(Set<String> res,String surround,String separator){
		if(res==null || res.size()==0){
			return "";
		}
		int size=res.size();
		String[] tmp=new String[size];
		res.toArray(tmp);
		return merge(tmp,surround,separator);
	}
	
	public static String merge(List<String> res,String surround,String separator){
		if(res==null || res.size()==0){
			return "";
		}
		int size=res.size();
		String[] tmp=new String[size];
		res.toArray(tmp);
		return merge(tmp,surround,separator);
	}
	
	public static String generateUUID(){
		return UUID.randomUUID().toString().toUpperCase();
	}
	
	
	
	/**
	 * yyyyMMdd
	 */
	public static final int DATE_CHARACTER_FORMAT_01=1;
	/**
	 * yyyy/MM/dd
	 */
	public static final int DATE_CHARACTER_FORMAT_02=2;
	/**
	 * yyyy-MM-dd
	 */
	public static final int DATE_CHARACTER_FORMAT_03=3;
	/**
	 * yyyy年MM月dd日
	 */
	public static final int DATE_CHARACTER_FORMAT_04=4;
	
	public static String convertDateCharacterFormat(Object res,int res_format,int target_format){
		if(res==null){
			return "";
		}
		if(!(res instanceof String)){
			return "";
		}
		return convertDateCharacterFormat(res.toString(),res_format,target_format);
	}
	
	/**
	 * 当为“-”时可直接输出
	 */
	public static String convertDateCharacterFormatWithLine(Object res,int res_format,int target_format){
		if(res==null){
			return "";
		}
		if("-".equals(res)){
			return "-";
		}
		if(!(res instanceof String)){
			return "";
		}
		return convertDateCharacterFormat(res.toString(),res_format,target_format);
	}
	public static String convertDateCharacterFormat(String res,int res_format,int target_format){
		if(res==null || "".equalsIgnoreCase(res.trim())){
			return "";
		}else{
			res=res.trim();
		}

		if(DATE_CHARACTER_FORMAT_01==res_format){
			if(DATE_CHARACTER_FORMAT_01==target_format){
				return res;
			} 
			
			String year=res.substring(0,4);
			String month=res.substring(4,6);
			String day=res.substring(6,8);
				
			if(DATE_CHARACTER_FORMAT_02==target_format){
				return year+"/"+month+"/"+day;
			}else if(DATE_CHARACTER_FORMAT_03==target_format){
				return year+"-"+month+"-"+day;
			}else if(DATE_CHARACTER_FORMAT_04==target_format){
				return year+"年"+month+"月"+day+"日";
			}
		}else if(DATE_CHARACTER_FORMAT_02==res_format){
			if(DATE_CHARACTER_FORMAT_02==target_format){
				return res;
			}
			String[] part=res.split("/");
			if(DATE_CHARACTER_FORMAT_01==target_format){
				return part[0]+part[1]+part[2];
			}else if(DATE_CHARACTER_FORMAT_03==target_format){
				return part[0]+"-"+part[1]+"-"+part[2];
			}else if(DATE_CHARACTER_FORMAT_04==target_format){
				return part[0]+"年"+part[1]+"月"+part[2]+"日";
			}
		}else if(DATE_CHARACTER_FORMAT_03==res_format){
			if(DATE_CHARACTER_FORMAT_03==target_format){
				return res;
			}
			
			String[] part=res.split("-");
			
			if(DATE_CHARACTER_FORMAT_01==target_format){
				return part[0]+part[1]+part[2];
			}else if(DATE_CHARACTER_FORMAT_02==target_format){
				return part[0]+"/"+part[1]+"/"+part[2];
			}else if(DATE_CHARACTER_FORMAT_04==target_format){
				return part[0]+"年"+part[1]+"月"+part[2]+"日";
			}
		}else if(DATE_CHARACTER_FORMAT_04==res_format){
			if(DATE_CHARACTER_FORMAT_04==target_format){
				return res;
			}
			
			String year=res.substring(0,4);
			String month=res.substring(5,7);
			String day=res.substring(8,10);
			
			if(DATE_CHARACTER_FORMAT_01==target_format){
				return year+month+day;
			}else if(DATE_CHARACTER_FORMAT_02==target_format){
				return year+"/"+month+"/"+day;
			}else if(DATE_CHARACTER_FORMAT_03==target_format){
				return year+"-"+month+"-"+day;
			}
		}
		return "";
	}
	public static String replaceEnter(String str){
		Pattern pattern = Pattern
				.compile("(\\\\r\\\\n|\\\\r|\\\\n|\\\\n\\\\r)");
		Matcher ma = null;
		str = StringEscapeUtils.escapeJava(str);
		if (str == null || "".equals(str)) {
			return null;
		}
		ma = pattern.matcher(str);
		if (ma.find()) {
			str = ma.replaceAll("</br>");
		}
		return  StringEscapeUtils.unescapeJava(str);
	
	}
	
	/**
	 * 文本域行替换
	 * @param source
	 * @return
	 */
	public static String replaceNewLineCharacter(String source) {
		String newLineCharacter = "\r\n";
		String newLineCharacter2 = "\\r\\n";
		String newLineCharacter3 = "\n";
		String newLineHtml = "<br/>";
		source = StringUtils.replace(source, newLineCharacter, newLineHtml);
		source = StringUtils.replace(source, newLineCharacter2, newLineHtml);
		source = StringUtils.replace(source, newLineCharacter3, newLineHtml);
		return source;
	}
	
	/**
	 * 文本域行替换
	 * @param source
	 * @return
	 */
	public static String replaceNewLineToEmpty(String source) {
		String newLineCharacter = "\r\n";
		String newLineCharacter2 = "\\r\\n";
		String newLineHtml = "";
		source = StringUtils.replace(source, newLineCharacter, newLineHtml);
		source = StringUtils.replace(source, newLineCharacter2, newLineHtml);
		return source;
	}
	
	public static String escapeHtml(String source) {
		if (StringUtils.isNotEmpty(source)) {
			char[] sourceChar = source.toCharArray();
			StringBuffer newString = new StringBuffer();
			for (int i = 0; i < sourceChar.length; i++) {
				Character.UnicodeBlock ub = Character.UnicodeBlock.of(sourceChar[i]);
				if (SPCIAL_SYMBOL_BLOCK.contains(ub)) {
					newString.append(StringEscapeUtils.escapeHtml(String.valueOf(sourceChar[i])));
				} else {
					newString.append(sourceChar[i]);
				}
			}
			source = newString.toString();
		}
		
		return source;
	}
	
	public static String trimParagraph(String source, String key, Set<String> richTextCodes) {
		if (StringUtils.isNotEmpty(source)) {
			StringBuffer buffer = new StringBuffer();
			String[] contentvalues2 = StringUtils.split(source, "\r\n");
			if (contentvalues2 != null && contentvalues2.length > 0) {
				for (int i = 0; i < contentvalues2.length; i++) {
					String trimed = StringUtils.trim(contentvalues2[i]);
					if (StringUtils.isNotEmpty(trimed) 
							&& !StringUtils.equals(trimed, "<br/>")
							&& !StringUtils.equals(trimed, "<br />")) {
						
						if (!richTextCodes.contains(key)) {
							trimed = trimed.replaceAll("\\s", "");
						} else {
							trimed = trimed.replaceAll("&nbsp;", "");
						}
						buffer.append(trimed);
						
						if (i != contentvalues2.length - 1) {
							buffer.append("\r\n");
						}
					}
				}
			}
			return buffer.toString();
		}
		return source;
	}

	/**
	 * @param defaultValue
	 * @return
	 */
	public static String addIndent(String source) {
		if (StringUtils.isEmpty(source)) {
			return "";
		}
		StringBuffer buffer = new StringBuffer();
		source = StringUtils.replace(source, "<br />", "<br/>");
		source = StringUtils.replace(source, "<br>", "<br/>");
		String[] paragraphs = StringUtils.splitByWholeSeparator(source, "<br/>");
		if (paragraphs != null && paragraphs.length > 1) {
			for (int i = 0; i < paragraphs.length; i++) {
				if (StringUtils.isNotBlank(paragraphs[i])) {
					buffer.append("<span style=3D'mso-tab-count:1'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>");
					buffer.append(paragraphs[i]);
					if (i != (paragraphs.length - 1)) {
						buffer.append("<br/>");
					}
				}
			}
		} else {
			buffer.append("<span style=3D'mso-tab-count:1'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>");
			buffer.append(source);
		}
		return buffer.toString();
	}
	
	/**
	 * 根据传入字符，判断是否删除第一个字符
	 * 
	 * @param charAt
	 * @param param
	 * @return
	 */
	public static String deleteFirstChar(char charAt, String param) {
		StringBuffer buffer = new StringBuffer(param);
		if (StringUtils.isNotBlank(param)) {
			if (charAt == (param.charAt(0))) {
				buffer.deleteCharAt(0);
			}
		}
		return buffer.toString();
	}
	
	/**
	 * 根据源字符，删除首、尾字符
	 * @param firstChar
	 * @param lastChar
	 * @param source
	 * @return
	 */
	public static String deleteFirstAndLastChar(char firstChar, char lastChar, String source) {
		source = deleteFirstChar(firstChar, source);
		source = deleteLastChar(lastChar, source);
		return source;
	}
	
	/**
	 * 转换特殊字符
	 * @param special
	 * @return
	 */
	public static String changeSpecialCharacter(String special){
		if(StringUtils.isNotEmpty(special)){
			List<DictionaryVo> type = DictionaryCached.getDictionaryByType("SPECIAL_CHARACTER");
			if(CollectionUtils.isNotEmpty(type)){
				for (DictionaryVo dictionaryVo : type) {
					if(special.contains(dictionaryVo.getDctName())){
						special = special.replaceAll(dictionaryVo.getDctName(), dictionaryVo.getDctValue());
					}
				}
			}
		}
		return special;
	}

	/**
	 * 截取字符串
	 * @param param
	 * @param length
	 * @return
	 */
	public static String subStringByLength(String param, int length) {
		if (StringUtils.isNotBlank(param)) {
			param = param.trim();
			if (param.length() > length) {
				return param.substring(0, length);
			}
		}
		return param;
	}

	/**
	 * <pre>
	 * <b>desc:</b> 移除字符串末尾多余的字符串
	 * <b>auth:</b> ex-hejm
	 * <b>date:</b> 2018年8月28日 上午10:34:43
	 * </pre>
	 * @param str
	 * @param chars
	 * @return
	 */
    public static String removeLastChars(String str, String chars) {
        if(StringUtils.isBlank(str)) {
            return str;
        }
        int lastIndexOf = str.lastIndexOf(chars);
        if(StringUtils.isBlank(chars) || str.length() - lastIndexOf != chars.length()) {
            return str;
        }
        String substring = str.substring(0, lastIndexOf);
        return substring;
    }
}
